package com.cps.match.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.cps.match.sdo.EnquiryResponse;
import com.cps.match.sdo.Principal;
import com.cps.match.sdo.PrincipalMatch;

public class MatchEnquiryDao {

	private SqlSessionFactory sqlSessionFactory;

	public MatchEnquiryDao() {
		sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
	}

	public List<EnquiryResponse> selectAll() {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			List<EnquiryResponse> list = session.selectList("EnquiryResponse.getAll");
			return list;
		} finally {
			session.close();
		}
	}

	public EnquiryResponse selectById(int id) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			EnquiryResponse contact = (EnquiryResponse) session.selectOne("EnquiryResponse.getById", id);
			return contact;
		} finally {
			session.close();
		}
	}
	
	public void insert(EnquiryResponse enquiryResponse) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			session.insert("EnquiryResponse.insert", enquiryResponse);
			//temporary solution: should try to use batch insert, but it 's not work with oracle, find another solution.
			for(Principal principal: enquiryResponse.getTerminatedMerchant().getMerchant().getPrincipal()) {
				Map<String, Object> principalParam = new HashMap<String, Object>();
				principalParam.put("enquiryId", enquiryResponse.getEnquiryId());
				principalParam.put("principal", principal);
				session.insert("EnquiryResponse.insertPrincipals", principalParam);
			}
			
			for(PrincipalMatch principalMatch: enquiryResponse.getTerminatedMerchant().getMerchantMatch().getPrincipalMatch()) {
				Map<String, Object> principalMatchParam = new HashMap<String, Object>();
				principalMatchParam.put("enquiryId", enquiryResponse.getEnquiryId());
				principalMatchParam.put("principalMatch", principalMatch);
				session.insert("EnquiryResponse.insertPrincipalMatchs", principalMatchParam);
			}

			session.commit();
		} finally {
			session.close();
		}
	}

}
